package suncertify.ui;


import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import suncertify.network.ServerHelper;
import suncertify.network.ServerInterface;
import suncertify.resources.App;

/**
 * A <code>WindowListener</code> that listens for events on the windows, 
 * then responds to those events.
 * @author Paul Wilhelm
 *
 */

public class WindowEventHandler implements WindowListener{
	
	private ServerInterface data;
	private Subscriber s;
	
	/**
	 * Constructor. Creates a new <code>WindowEventHandler</code> object and listens
	 * to events on the provided <code>Subscriber</code>.
	 * @param s - The subscriber object that will be handled
	 */
	public WindowEventHandler(Subscriber s){
		this.s = s;
		data = ServerHelper.getRemoteDatabase();
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowActivated(WindowEvent e) {
		//No need to implement
	}
	
	/**
	 * {@inheritDoc}
	 */
	public void windowClosed(WindowEvent e) {
		try {
			List<Subscriber> newList = new ArrayList<Subscriber>();
			for (Subscriber sub: App.localList){
				if (sub.equals(s)){
					continue;
				}
				newList.add(sub);
			}
			App.localList = newList;
			data.unSubscribe(s);
			
			if (s.getTitle().equals("URLy Bird Hotel Booking")){
				for (Subscriber sub: App.localList){			//Unsubscribes each element of the local list before completely closing the app.
					data.unSubscribe(sub);
				}
				System.exit(0);
			}
		} catch (RemoteException e1) {
			JOptionPane.showMessageDialog(null, "There was a problem un-subscribing this window.  You'll need to restart the server" +
					"synchronize it again.");
			e1.printStackTrace();
			System.exit(0);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowClosing(WindowEvent e){
		windowClosed(e);
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowDeactivated(WindowEvent e) {
		//No need to implement
		
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowDeiconified(WindowEvent e) {
		//No need to implement
		
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowIconified(WindowEvent e) {
		//No need to implement
		
	}

	/**
	 * {@inheritDoc}
	 */
	public void windowOpened(WindowEvent e) {
		//No need to implement
	}

}
